package com.project.dao.Impl;

import com.project.bean.InvitationBane;
import com.project.bean.SpeakBean;
import com.project.bean.UserBean;
import com.project.dao.ISpeakDao;
import com.project.dao.IUserDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class SpeakDaoImpl extends BaseDao implements ISpeakDao {
    IUserDao dao=new UserDaoImpl();
    @Override
    public void addSpeak(SpeakBean speak) {
        this.setConnection();
        try {
            ps=con.prepareStatement("INSERT INTO s_speak(s_name,s_content,s_date,fk_userId,fk_inId)\n" +
                    "VALUES(?,?,?,?,?)");
            ps.setObject(1,speak.getName());
            ps.setObject(2,speak.getContent());
            ps.setObject(3,speak.getDate());
            ps.setObject(4,speak.getUser().getId());
            ps.setObject(5,speak.getIn().getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
    }

    @Override
    public List<SpeakBean> findAll(Integer inId) {
        List<SpeakBean> list=new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT s.* FROM s_speak s LEFT JOIN t_invitation t ON s.fk_inId=t.pk_inId WHERE  fk_inId=?");
            ps.setObject(1,inId);
            rs=ps.executeQuery();
            while (rs.next()){
                SpeakBean speakBean = new SpeakBean();
                speakBean.setId(rs.getInt("pk_speakId"));
                speakBean.setContent(rs.getString("s_content"));
                UserBean user = dao.findById(rs.getInt("fk_userId"));
                UserBean userBean = new UserBean();
                userBean.setId(rs.getInt("fk_userId"));
                speakBean.setUser(user);
                speakBean.setDate(LocalDate.parse(rs.getString("s_date")));
                InvitationBane in = new InvitationBane();
                in.setId(rs.getInt("fk_inId"));
                speakBean.setIn(in);
                list.add(speakBean);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return list;
    }
}
